package com.junjie.shortlink.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.junjie.shortlink.admin.common.biz.user.UserContext;
import com.junjie.shortlink.admin.common.convention.exception.ClientException;
import com.junjie.shortlink.admin.common.convention.result.Result;
import com.junjie.shortlink.admin.common.convention.result.Results;
import com.junjie.shortlink.admin.common.enums.UserErrorCodeEnum;
import com.junjie.shortlink.admin.dao.entity.UserDO;
import com.junjie.shortlink.admin.dao.mapper.UserMapper;
import com.junjie.shortlink.admin.dto.req.UserLoginReqDTO;
import com.junjie.shortlink.admin.dto.req.UserRegisterReqDTO;
import com.junjie.shortlink.admin.dto.req.UserUpdateReqDTO;
import com.junjie.shortlink.admin.dto.resp.UserLoginRespDTO;
import com.junjie.shortlink.admin.dto.resp.UserRespDTO;
import com.junjie.shortlink.admin.service.GroupService;
import com.junjie.shortlink.admin.service.UserService;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import static com.junjie.shortlink.admin.common.constant.RedisCacheConstant.LOCK_USER_REGISTER_KEY;
import static com.junjie.shortlink.admin.common.constant.RedisCacheConstant.USER_LOGIN_KEY;
import static com.junjie.shortlink.admin.common.enums.UserErrorCodeEnum.*;

@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService {

    private final RBloomFilter<String> userRegisterCachePenetrationBloomFilter;
    private final RedissonClient redissonClient;
    private final StringRedisTemplate stringRedisTemplate;
    private final GroupService groupService;

    @Override
    public UserRespDTO getUserByUsername(String username) {
        LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getUsername, username);
        UserDO userDO = baseMapper.selectOne(queryWrapper);
        if (userDO == null) {
            throw new ClientException(UserErrorCodeEnum.USER_NULL);
        }
        UserRespDTO result = new UserRespDTO();
        BeanUtils.copyProperties(userDO, result);
        return result;
    }

    @Override
    public Boolean hasUsername(String username) {
//        UserDO userDO = this.getOne(Wrappers.lambdaQuery(UserDO.class).eq(UserDO::getUsername, username));
//        return userDO == null;

        // 直接改用布隆过滤器判断用户名是否存在
        return !userRegisterCachePenetrationBloomFilter.contains(username);
    }

    @Override
    public void register(UserRegisterReqDTO requestParam) {
        if (!hasUsername(requestParam.getUsername())) {
            throw new ClientException(USER_NAME_EXIST);
        }
        // 分布式锁避免并发注册同一用户名
        RLock lock = redissonClient.getLock(LOCK_USER_REGISTER_KEY + requestParam.getUsername());
        if (!lock.tryLock()) { // 如果获取不到锁就直接抛出异常
            throw new ClientException(USER_NAME_EXIST);
        }
        try {
            int insert = baseMapper.insert(BeanUtil.toBean(requestParam, UserDO.class));
            if (insert < 1) { // 这里其实都不可能进得去，因为已经用了分布式锁了
                throw new ClientException(USER_SAVE_ERROR);
            }
            // keypoint 新增数据库放在新增布隆过滤器上放，避免新增布隆失败，但是新增数据库事务回滚了
            // 新用户应该有个默认分组
            groupService.saveGroup(requestParam.getUsername(), "默认分组");
            // 注册完的用户添加到布隆过滤器
            userRegisterCachePenetrationBloomFilter.add(requestParam.getUsername());
        } catch (DuplicateKeyException ex) { // 如果插入报错就提示用户记录已存在
            throw new ClientException(USER_EXIST);
        } finally {
            // 如果没有tryLock然后还来unLock的话，就会抛出异常
            lock.unlock();
        }

    }

    @Override
    public void update(UserUpdateReqDTO requestParam) {
        // 校验前端传来的userName，其实都不应该由前端传来
        if(!Objects.equals(requestParam.getUsername(), UserContext.getUsername())){
            throw new ClientException("当前登录用户修改请求异常");
        }
        // TODO 验证当前用户名是否为登录用户
        LambdaUpdateWrapper<UserDO> updateWrapper = Wrappers.lambdaUpdate(UserDO.class)
                .eq(UserDO::getUsername, requestParam.getUsername());
        baseMapper.update(BeanUtil.toBean(requestParam, UserDO.class), updateWrapper);
    }

    // 这种是多地多端登录的
    @Override
    public UserLoginRespDTO login(UserLoginReqDTO requestParam) {
        LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getUsername, requestParam.getUsername())
                .eq(UserDO::getPassword, requestParam.getPassword())
                .eq(UserDO::getDelFlag, 0);
        UserDO userDO = baseMapper.selectOne(queryWrapper);
        if (userDO == null) {
            throw new ClientException("用户不存在");
        }
        // 如果想做单点登录的话，这里就要改成获取出用户登录数据后，判断一下，如果有，就抛出异常说用户已登录
        // 获取出hash所有的值
        Map<Object, Object> hasLoginMap = stringRedisTemplate.opsForHash().entries(USER_LOGIN_KEY + requestParam.getUsername());
        // 如果有token直接返回给前端
        if (CollUtil.isNotEmpty(hasLoginMap)) {
            // keypoint 同时刷新token有效时间为30分钟，之所以要刷新，是因为引入网关后，访问中台出现
            //  两种方案，一个是密钥方式，但是对源代码改动比较大，另一种是和后管沿用一个方案，就是每次
            //  都带上用户TOKEN访问中台接口即可。不过这样的话，如果TOKEN突然过期，就会导致有一段时间，
            //  真空期，因此可以这样，让调用中台的人起一个定时任务，定时多久调用一次login接口，再接着
            //  调用他想访问的接口，就可以做到TOKEN无感知了
            stringRedisTemplate.expire(USER_LOGIN_KEY + requestParam.getUsername(), 30L, TimeUnit.MINUTES);
            String token = hasLoginMap.keySet().stream()
                    .findFirst()
                    .map(Object::toString)
                    .orElseThrow(() -> new ClientException("用户登录错误"));
            return new UserLoginRespDTO(token);
        }
        /**
         * Hash
         * Key：login_用户名
         * Value：
         *  Key：token标识
         *  Val：JSON 字符串（用户信息）
         */
        String uuid = UUID.randomUUID().toString();
        // hash结构 第一个参数是大key 第二个参数才是具体hashKey
        stringRedisTemplate.opsForHash().put(USER_LOGIN_KEY + requestParam.getUsername(), uuid, JSON.toJSONString(userDO));
        stringRedisTemplate.expire(USER_LOGIN_KEY + requestParam.getUsername(), 30L, TimeUnit.HOURS);
        return new UserLoginRespDTO(uuid);
    }

    @Override
    public Boolean checkLogin(String username, String token) {
        return stringRedisTemplate.opsForHash().get(USER_LOGIN_KEY + username, token) != null;
    }

    @Override
    public void logout(String username, String token) {
        if (checkLogin(username, token)) {
            stringRedisTemplate.delete(USER_LOGIN_KEY + username);
            return;
        }
        throw new ClientException("用户Token不存在或用户未登录");
    }


}
